﻿using System;
using System.Net;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;

using SBPweb.Common.Connectivity;

namespace SBPweb.Services.Crawlers.Base
{
    public abstract class ParsingClientBase// : WebClient
    {

        #region Private fields

        private bool lastBusyState = true;

        private CookiedWebClient webClient;

        protected Uri baseUri;

        #endregion

        #region Constructor logic

        public ParsingClientBase(Uri baseUri)
        {
            webClient = new CookiedWebClient();
            this.baseUri = baseUri;
            webClient.BaseAddress = baseUri.AbsoluteUri;
            webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(ParsingClientBase_DownloadDataCompleted);
            webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(ParsingClientBase_DownloadFileCompleted);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ParsingClientBase_DownloadStringCompleted);
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(ParsingClientBase_OpenReadCompleted);
            webClient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(ParsingClientBase_OpenWriteCompleted);
            webClient.UploadDataCompleted += new UploadDataCompletedEventHandler(ParsingClientBase_UploadDataCompleted);
            webClient.UploadFileCompleted += new UploadFileCompletedEventHandler(ParsingClientBase_UploadFileCompleted);
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(ParsingClientBase_UploadStringCompleted);
            webClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler(ParsingClientBase_UploadValuesCompleted);
        }

        #endregion

        #region Property accessors

        public bool IsBusy
        {
            get
            {
                return webClient.IsBusy;
            }
        }

        #endregion

        #region Events

        public event EventHandler IsIdle;

        #endregion

        #region Methods
        
        public string ParseRequest(Uri uri)
        {
            return ParseRequest(uri, null);
        }

        public string ParseRequest(Uri uri, string formName)
        {
            webClient.HeaderOverrides.Add(HttpRequestHeader.ContentType, "multipart/form-data");
            if (!string.IsNullOrEmpty(formName))
            {
                webClient.Headers.Add("Content-Disposition", "form-data; name=\"" + formName + "\"");
            }
            else
            {
                webClient.Headers.Add("Content-Disposition", "form-data");
            }
            return webClient.UploadString(uri, "POST", string.Empty);
        }

        //public string PostRequest(Uri uri, Dictionary<string, string> formValues)
        //{
        //    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
        //    return webClient.UploadString(uri, "POST", GetPostData(formValues));
        //}

        #region Completed event handlers

        private void RaiseIdleChangedHandlers(EventArgs e)
        {
            lock (webClient)
            {
                if (IsIdle != null && !webClient.IsBusy && lastBusyState)
                {
                    IsIdle(this, e);
                }
                lastBusyState = webClient.IsBusy;
            }
        }

        private void ParsingClientBase_UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        private void ParsingClientBase_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            RaiseIdleChangedHandlers(e);
        }

        #endregion

        #region Private helper functions

        //private string GetPostData(Dictionary<string, string> formValues)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    foreach (KeyValuePair<string, string> kvp in formValues)
        //    {
        //        if (sb.Length > 0)
        //        {
        //            sb.Append("&");
        //        }
        //        sb.Append(string.Format("{0}={1}", kvp.Key, kvp.Value));
        //    }
        //    return sb.ToString();
        //}

        #endregion

        #endregion

    }
}
